package com.hfjyz.registration.controller;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

import com.hfjyz.registration.command.RegistCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.model.Apply;
import com.hfjyz.registration.model.Depart;
import com.hfjyz.registration.model.Exam;
import com.hfjyz.registration.model.Office;
import com.hfjyz.registration.model.User;
import com.hfjyz.registration.service.RegistService;
import com.hfjyz.registration.util.MasterUtil;
import com.hfjyz.registration.validator.RegistValidator;

public class RegistWizardController extends AbstractWizardFormController {

	private RegistService registService;

	private String successView;
	private String cancelView;

	public String getCancelView() {
		return cancelView;
	}

	public void setCancelView(String cancelView) {
		this.cancelView = cancelView;
	}

	public String getSuccessView() {
		return successView;
	}

	public void setSuccessView(String successView) {
		this.successView = successView;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#
	 * referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object,
	 * org.springframework.validation.Errors, int)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors, int page) throws Exception {
		RegistCommand cmd = (RegistCommand) command;
		Exam examInfo = (Exam) request.getSession().getAttribute(
				ExamContants.SESSION_KEY_EXAM_INFO);
		cmd.setExam(examInfo);
		if (page == 0) {
			String editFlg = request.getParameter("editFlg");
			if (editFlg != null && !editFlg.isEmpty()) {
				cmd.setEditFlg(editFlg);
			}
			cmd.setExams(Arrays.asList(new Exam[] { examInfo }));
			Date today = Calendar.getInstance().getTime();
			for (Exam exam : cmd.getExams()) {
				if (!"1".equals(editFlg)
						&& today.after(exam.getApplyDeadDate())) {
					throw new Exception("很抱歉，报名已经结束！");
				} else if (today.before(exam.getApplyBeginDate())) {
					throw new Exception("报名还未开始，请耐心等待！");
					// } else if ("1".equals(editFlg)
					// && (today.after(exam.getReApplyEnd()) || today
					// .before(exam.getReApplyStart()))) {
					// throw new Exception("信息修改时间已结束，无法修改！");
				}
			}
			if (!errors.hasErrors()) {
				cmd.setSexs(MasterUtil.getInstance().getMasters(1));
				cmd.setMarriedStates(MasterUtil.getInstance().getMasters(2));
				cmd.setPoliticalCodes(MasterUtil.getInstance().getMasters(3));
				cmd.setIdentities(MasterUtil.getInstance().getMasters(4));
				cmd.setNationCodes(MasterUtil.getInstance().getMasters(5));
				cmd.setDegrees(MasterUtil.getInstance().getMasters(7));
				cmd.setComputerSkills(MasterUtil.getInstance().getMasters(9));
				cmd.setLanguageSkills(MasterUtil.getInstance().getMasters(8));
				cmd.setDeparts(registService.listDepart(examInfo));
				cmd.setOffices(registService.listOffice(examInfo));
			}
		}
		return super.referenceData(request, command, errors, page);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#
	 * postProcessPage(javax.servlet.http.HttpServletRequest, java.lang.Object,
	 * org.springframework.validation.Errors, int)
	 */
	@Override
	protected void postProcessPage(HttpServletRequest request, Object command,
			Errors errors, int page) throws Exception {
		RegistCommand cmd = (RegistCommand) command;
		Exam exam = (Exam) request.getSession().getAttribute(
				ExamContants.SESSION_KEY_EXAM_INFO);
		cmd.setExam(exam);
		if (page == 0 && !errors.hasErrors()) {
			String idCardNo = cmd.getIdCardNo();
			User user = registService.findIdCardNo(idCardNo, exam.getId());
			if (user != null) {
				cmd.setUserId(user.getId());
				cmd.setName(user.getName());
				// cmd.setPassword(user.getPassword());
				cmd.setIdCardNo(user.getIdCardNo());
				cmd.setSexCode(String.valueOf(user.getSex()));
				cmd.setNationCode(String.valueOf(user.getNationCode()));
				cmd.setHomeTown(user.getHomeTown());
				cmd.setBirthdayMonth(user.getBirthdayMonth());
				cmd.setBirthdayYear(user.getBirthdayYear());
				cmd.setPoliticalCode(String.valueOf(user.getPoliticalCode()));
				cmd.setIdentity(String.valueOf(user.getIdentity()));
				cmd.setIsMarried(String.valueOf(user.getMarried()));
				cmd.setDegree(user.getDegree());
				cmd.setUserSchool(user.getGraduateSchool());
				cmd.setGraduateYear(String.valueOf(user.getGraduateYear()));
				cmd.setGraduateMonth(String.valueOf(user.getGraduateMonth()));
				cmd.setWorkYears(String.valueOf(user.getWorkyears()));
				cmd.setUserMajor(user.getMajor());
				cmd.setComputerSkill(user.getComputerSkill());
				cmd.setLanguageSkill(user.getLanguageSkill());
				cmd.setTelephone(user.getTelephone());
				cmd.setHeight(String.valueOf(user.getHeight()));
				cmd.setTrainingExp(user.getTrainingExp());
				cmd.setWorkExp(user.getWorkExp());
				cmd.setSocialRel(user.getSocialRel());
				cmd.setPhoto(user.getPhoto());

				Apply apply = registService.getApply(user.getId(), cmd
						.getExam().getId());
				if (apply != null) {
					Integer applyPostId = apply.getId().getOfficeid();
					int state = apply.getState();
					if (state == 2) {
						throw new Exception("申请已审核完毕，无法修改！");
						// errors.reject("error", "");
						// super.postProcessPage(request,
						// com.hfjyz.registration.command, errors,
						// page);
						// return ;
					}
					if (applyPostId != null) {
						Office office = null;
						for (Office dbOffice : cmd.getOffices()) {
							if (dbOffice.getId().equals(applyPostId)) {
								office = dbOffice;
							}
						}
						cmd.setApplyPostId(String.valueOf(applyPostId));
						// Office office = registService.getOffice(applyPostId);
						if (office != null) {
							cmd.setApplyPostCode(office.getCode());
							cmd.setApplyDeptId(String.valueOf(office
									.getDepartId()));
							cmd.setApplyDeptName(office.getDepartName());
							for (Exam dbExam : cmd.getExams()) {
								if (dbExam.getId().equals(office.getExamId())) {
									cmd.setRegistExamCode(String.valueOf(dbExam
											.getId()));
									cmd.setRegistExamName(dbExam.getName());
									cmd.setRegistExamLocation(dbExam
											.getExamPosition());
									break;
								}
							}
						}
					}

				}

				request.getSession().setAttribute(
						"photoData" + cmd.getIdCardNo(), user.getPhoto());
			}
		} else if (page == 1) {
			String examId = cmd.getRegistExamCode();
			for (Exam exam1 : cmd.getExams()) {
				if (examId.equals(String.valueOf(exam1.getId()))) {
					cmd.setRegistExamName(exam1.getName());
					cmd.setRegistExamLocation(exam1.getExamPosition());
				}
			}
		} else if (page == 4) {
			String departId = cmd.getApplyDeptId();
			for (Depart depart : cmd.getDeparts()) {
				if (departId.equals(String.valueOf(depart.getId()))) {
					// cmd.setApplyCityId(depart.getCityName());
					cmd.setApplyDeptName(depart.getName());
				}
			}
			String officeId = cmd.getApplyPostId();
			for (Office office : cmd.getOffices()) {
				if (officeId.equals(String.valueOf(office.getId()))) {
					cmd.setApplyPostName(office.getName());
					cmd.setApplyPostCode(office.getCode());
				}
			}
		} else if (page == 5) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest
					.getFile("uploadPhoto");
			if (multipartFile != null && !multipartFile.isEmpty()) {
				if (multipartFile.getSize() > 102400) {
					errors.reject("uploadPhoto", "上传的图片太大");
				} else {

					// InputStream in = multipartFile.getInputStream();
					// ByteArrayOutputStream out = new ByteArrayOutputStream();
					// byte[] buff = new byte[8192];
					// int len = 0;
					// while ((len = in.read(buff, 0, 8192)) != -1) {
					// out.write(buff, 0, len);
					// }
					// out.flush();
					// out.close();
					// in.close();

					cmd.setPhoto(multipartFile.getBytes());
					request.getSession().setAttribute(
							"photoData" + cmd.getIdCardNo(), cmd.getPhoto());
				}

			}
		}
		super.postProcessPage(request, command, errors, page);
	}

	protected ModelAndView processCancel(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, BindException arg3)
			throws Exception {

		// registService.add(null);
		return new ModelAndView(this.getCancelView());
	}

	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object object, BindException exception)
			throws Exception {
		RegistCommand vote = (RegistCommand) object;
		if ("1".equals(vote.getEditFlg())) {
			registService.loggin(request, ExamContants.LOGING_TYPE_INFO,
					(Integer) vote.getUserId(),
					ExamContants.LOGING_USER_TYPE_USER, vote.getIdCardNo(),
					ExamContants.LOGING_OP_TYPE_EDIT, "报名信息修改");
		} else {
			registService
					.loggin(request, ExamContants.LOGING_TYPE_INFO,
							(Integer) null, ExamContants.LOGING_USER_TYPE_USER,
							vote.getIdCardNo(),
							ExamContants.LOGING_OP_TYPE_ADD, "网上报名");
		}
		registService.add(vote);
		return new ModelAndView(this.getSuccessView(), "vote", vote);
	}

	protected void validatePage(Object command, Errors errors, int page) {
		RegistCommand vote = (RegistCommand) command;
		RegistValidator validator = (RegistValidator) getValidator();

		switch (page) {
		case 0:
			User idCardNoLst = null;
			try {
				if (vote.getIdCardNo() != null && vote.getExam() != null) {
					idCardNoLst = registService.findIdCardNo(
							vote.getIdCardNo(), vote.getExam().getId());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			validator.validateRegistInfo(vote, errors, idCardNoLst);
			break;
		case 1:
			String examId = vote.getRegistExamCode();
			if (examId != null) {
				try {
					List<Depart> departs = registService
							.getDepartByExamId(examId);
					if (departs != null && departs.size() != 0) {
						List<Office> offices = registService
								.getOfficeByExamId(examId);
						if (offices == null || offices.size() == 0) {
							validator.validateId(vote, errors, 2);
						}
					} else {
						validator.validateId(vote, errors, 1);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		case 3:
			validator.validatePeopleInfo(vote, errors);
			break;
		default:
			return;
		}

	}

	/**
	 * @return the registService
	 */
	public RegistService getRegistService() {
		return registService;
	}

	/**
	 * @param registService
	 *            the registService to set
	 */
	public void setRegistService(RegistService registService) {
		this.registService = registService;
	}
}